package com.tengju.settlement.domain.model.account;

import com.tengju.settlement.domain.shared.Amount;
import com.tengju.settlement.domain.shared.DomainException;
import com.tengju.settlement.domain.shared.DomainExceptionCode;
import com.tengju.settlement.domain.shared.Entity;
import lombok.Value;
import lombok.experimental.NonFinal;

import java.math.BigDecimal;

@Value
public class Account implements Entity<Account> {

    AccountId accountId;

    UserIdCode idCode;

    AccountType accountType;

    @NonFinal
    Amount balance;
    @NonFinal
    Amount freezeBalance;

    String mobile;
    @NonFinal
    Integer version;

    @Override
    public boolean sameIdentityAs(Account other) {
        return other != null && accountId != null && accountId.sameValueAs(other.accountId);
    }

    public static Account newAccount(UserIdCode idCode){
        return new Account(null, idCode,
                AccountType.DATA_TREE,
                new Amount(BigDecimal.valueOf(0)),
                new Amount(BigDecimal.valueOf(0)),
                null,null
        );
    }


    public void rollbackFreezeBalance(Amount amount) {
        if (amount.compareTo(freezeBalance) > 0) {
            throw DomainException.error(DomainExceptionCode.ACCOUNT_FREEZE_BALANCE_INSUFFICIENT);
        }
        freezeBalance = freezeBalance.subtract(amount);
        balance = balance.add(amount);
        version = version + 1;
    }


    public void plusBalance(Amount amount) {
        balance = balance.add(amount);
        version = version + 1;
    }

    public static void main(String[] args) {
        BigDecimal balance = BigDecimal.ZERO;
        balance = balance.add(BigDecimal.ONE);
        System.out.println(balance);
    }
}